package com.zrrd.learn.chapter03;

/**
 * 二分法
 *
 * @author wrn
 * @version 1.0
 * @date 2023/5/13 14:51
 */

public class BinarySearch {

    /**
     * 假如说有一组 有序地数
     * @param start 开始
     * @param end   末尾
     * @param target 目标
     * @return true|false
     */
    public static  boolean binarySearch(int start, int end, int target){

        checkException(start,end);
        return binarySearchReal(start, end, target);
    }
    /**
     * 容错 处理
     * @param start 开始
     * @param end   结尾
     * @return
     */
    public static void checkException(int start, int end) {
        if (start > end){
            throw   new RuntimeException("参数有问题");
        }
    }

    /**
     * 计算功能
     * @param start
     * @param end
     * @param target
     * @return
     */
    public static  boolean binarySearchReal(int start, int end, int target){

        if (start == end){
            return start == target;
        }

        while (start <= end){
            int middle = (end + start) >> 1;
            if (middle == target){
                return true;
            }else if (middle < target){
                start = middle + 1;
            }else {
                end = middle - 1;
            }
        }
        return false;
    }



    public static void main(String[] args) {
        System.out.println(binarySearch(1,10,17));
    }

}
